package com.byx.imserverutil.netty;

import com.byx.imserverutil.protobuf.ChatMessageProtobuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * NettyWebSocketChannelInitializer
 *
 * @author Superb
 * @date 2021/2/9 13:43
 */
public class NettyWebSocketChannelInitializer extends ChannelInitializer<Channel> {
    private final NettyWebSocketImServiceImpl imService;

    public NettyWebSocketChannelInitializer(NettyWebSocketImServiceImpl imService) {
        this.imService = imService;
    }

    @Override
    protected void initChannel(Channel channel) {
        ChannelPipeline pipeline=channel.pipeline();
        pipeline.addLast(new ProtobufDecoder(ChatMessageProtobuf.Msg.getDefaultInstance()));
        pipeline.addLast(new ProtobufEncoder());
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new ServerIdleStateTrigger());
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        pipeline.addLast(new NettyWebSocketHandler(imService));
//        pipeline.addLast(new NettyHeartBeatHandler());
        pipeline.addLast(new IdleStateHandler(4,8,12));
    }
}
